package com.ice.work.moment.ticket.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.honeybee.cloud.framework.base.exception.business.BaseBizException;
import com.honeybee.cloud.framework.common.http.HttpClient;
import com.honeybee.cloud.framework.common.http.HttpHeaderEnum;
import com.ice.work.moment.facade.ticket.constant.SystemConstant;
import com.ice.work.moment.facade.ticket.constant.TicketUrl;
import com.ice.work.moment.facade.ticket.dto.CarDTO;
import com.ice.work.moment.facade.ticket.dto.TicketDTO;
import com.ice.work.moment.facade.ticket.enums.SeatTypeEnum;
import com.ice.work.moment.facade.ticket.enums.UserAgentEnum;
import com.ice.work.moment.facade.ticket.param.QueryTicketParam;
import com.ice.work.moment.facade.ticket.response.QueryTicketResponse;
import com.ice.work.moment.ticket.service.ITicketService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.impl.client.BasicCookieStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.ice.work.moment.facade.ticket.enums.TicketBizExceptionEnum.REQUEST_EXP;
import static com.ice.work.moment.facade.ticket.enums.TicketBizExceptionEnum.RESPONSE_NULL;

/**
 * @Description 车票
 * @Author DELL
 * @Create 2019-05-29
 * @Since 1.0.0
 */
@Service
@Slf4j
public class TicketServiceImpl implements ITicketService {

    @Autowired
    private HttpClient httpClient;

    @Override
    public List<CarDTO> queryTicket(BasicCookieStore cookieStore, QueryTicketParam param) throws BaseBizException {
        log.info("开始查询车票");
        String url = String.format(TicketUrl.LEFT_TICKET_URL, param.getTrainDate(), param.getFromStation(), param.getToStation(), param.getTicketType());
        try {
            Map<String, String> header = Maps.newHashMap();
            header.put(HttpHeaderEnum.AGENT.value, UserAgentEnum.AGENT_12306.code);
            header.put(HttpHeaderEnum.HOST.value, TicketUrl.HOST_12306_URL);
            header.put(HttpHeaderEnum.REFERER.value, TicketUrl.QUERY_INIT_PAGE);
            header.put(HttpHeaderEnum.ACCEPT.value, SystemConstant.ACCEPT);
            header.put(HttpHeaderEnum.CONNECTION.value, SystemConstant.CONNECTION);
            header.put(HttpHeaderEnum.ENCODING.value, SystemConstant.ENCODING);
            header.put(HttpHeaderEnum.LANGUAGE.value, SystemConstant.LANGUAGE);
            String result = httpClient.sendGet(cookieStore, url, header);
            QueryTicketResponse response = JSONObject.parseObject(result, QueryTicketResponse.class);
            if (Objects.isNull(response)) {
                throw new BaseBizException(RESPONSE_NULL.getParentCode(), RESPONSE_NULL.getSubCode(), RESPONSE_NULL.getMessage());
            }
            if (Objects.isNull(response.getData())) {
                throw new BaseBizException(RESPONSE_NULL.getParentCode(), RESPONSE_NULL.getSubCode(), RESPONSE_NULL.getMessage());
            }
            return handleTicket(response.getData().getResult());
        } catch (Exception e) {
            log.error("查询车票信息异常", e);
            throw new BaseBizException(REQUEST_EXP.getParentCode(), REQUEST_EXP.getSubCode(), REQUEST_EXP.getMessage());
        }
    }

    private List<CarDTO> handleTicket(List<String> tickets) {
        if (CollectionUtils.isEmpty(tickets)) {
            return null;
        }
        List<CarDTO> carDTOs = Lists.newArrayList();
        for (String ticket : tickets) {
            if (StringUtils.isBlank(ticket)) {
                continue;
            }
            String[] args = ticket.split("\\|");
            CarDTO dto = getCar(args);
            if (Objects.nonNull(dto)) {
                carDTOs.add(dto);
            }
        }
        return carDTOs;
    }


    /**
     * 参考
     * var cR = [];
     * var cL = cO[cM].split("|");
     * cR.secretStr = cL[0];
     * cR.buttonTextInfo = cL[1];
     * var cP = [];
     * cP.train_no = cL[2];
     * cP.station_train_code = cL[3];
     * cP.start_station_telecode = cL[4];
     * cP.end_station_telecode = cL[5];
     * cP.from_station_telecode = cL[6];
     * cP.to_station_telecode = cL[7];
     * cP.start_time = cL[8];
     * cP.arrive_time = cL[9];
     * cP.lishi = cL[10];
     * cP.canWebBuy = cL[11];
     * cP.yp_info = cL[12];
     * cP.start_train_date = cL[13];
     * cP.train_seat_feature = cL[14];
     * cP.location_code = cL[15];
     * cP.from_station_no = cL[16];
     * cP.to_station_no = cL[17];
     * cP.is_support_card = cL[18];
     * cP.controlled_train_flag = cL[19];
     * cP.gg_num = cL[20] ? cL[20] : "--";
     * cP.gr_num = cL[21] ? cL[21] : "--";
     * cP.qt_num = cL[22] ? cL[22] : "--";
     * cP.rw_num = cL[23] ? cL[23] : "--";
     * cP.rz_num = cL[24] ? cL[24] : "--";
     * cP.tz_num = cL[25] ? cL[25] : "--";
     * cP.wz_num = cL[26] ? cL[26] : "--";
     * cP.yb_num = cL[27] ? cL[27] : "--";
     * cP.yw_num = cL[28] ? cL[28] : "--";
     * cP.yz_num = cL[29] ? cL[29] : "--";
     * cP.ze_num = cL[30] ? cL[30] : "--";
     * cP.zy_num = cL[31] ? cL[31] : "--";
     * cP.swz_num = cL[32] ? cL[32] : "--";
     * cP.srrb_num = cL[33] ? cL[33] : "--";
     * cP.yp_ex = cL[34];
     * cP.seat_types = cL[35];
     * cP.exchange_train_flag = cL[36];
     * cP.houbu_train_flag = cL[37];
     * if (cL.length > 38) {
     * cP.houbu_seat_limit = cL[38]
     * }
     * cP.from_station_name = cQ[cL[6]];
     * cP.to_station_name = cQ[cL[7]];
     */
    private CarDTO getCar(String[] args) {
        if (ArrayUtils.isEmpty(args)) {
            return null;
        }
        log.info("车次信息:{}", args);
        CarDTO carDTO = new CarDTO();
        carDTO.setSecretStr(args[0]);
        carDTO.setButtonTextInfo(args[1]);
        carDTO.setTrainNo(args[2]);
        carDTO.setStartStationCode(args[3]);
        carDTO.setStartStationCode(args[4]);
        carDTO.setEndStationCode(args[5]);
        carDTO.setFromStationCode(args[6]);
        carDTO.setToStationCode(args[7]);
        carDTO.setStartAt(args[8]);
        carDTO.setArrivalAt(args[9]);
        carDTO.setConsumingTime(args[10]);
        carDTO.setCanBook(args[11]);
        carDTO.setTicketInfo(args[12]);
        carDTO.setStartTrainDate(args[13]);
        carDTO.setTrainSeatFeature(args[14]);
        carDTO.setLocationCode(args[15]);
        carDTO.setFromStationNo(args[16]);
        carDTO.setToStationNo(args[17]);
        carDTO.setSupportCard(args[18]);
        carDTO.setControlledTrainFlag(args[19]);
        carDTO.setTicketList(getTicket(args));
        carDTO.setTicketExInfo(args[34]);
        carDTO.setSeatTypes(args[35]);
        carDTO.setExchangeTrainFlag(args[36]);
        carDTO.setAlternateTrainFlag(args[37]);
        if (ArrayUtils.getLength(args) > SystemConstant.TICKET_INFO_LENGTH) {
            carDTO.setAlternateSeatLimit(args[38]);
        }
        return carDTO;
    }

    private List<TicketDTO> getTicket(String[] args) {
        List<TicketDTO> ticketDTOS = Lists.newArrayList();
        TicketDTO ticketDTO = new TicketDTO();
        ticketDTO.setType(SeatTypeEnum.GG.code);
        ticketDTO.setNumber(args[20]);
        ticketDTOS.add(ticketDTO);
        ticketDTO = new TicketDTO();
        ticketDTO.setType(SeatTypeEnum.GR.code);
        ticketDTO.setNumber(args[21]);
        ticketDTOS.add(ticketDTO);
        ticketDTO = new TicketDTO();
        ticketDTO.setType(SeatTypeEnum.QT.code);
        ticketDTO.setNumber(args[22]);
        ticketDTOS.add(ticketDTO);
        ticketDTO = new TicketDTO();
        ticketDTO.setType(SeatTypeEnum.RW.code);
        ticketDTO.setNumber(args[23]);
        ticketDTOS.add(ticketDTO);
        ticketDTO = new TicketDTO();
        ticketDTO.setType(SeatTypeEnum.RZ.code);
        ticketDTO.setNumber(args[24]);
        ticketDTOS.add(ticketDTO);
        ticketDTO = new TicketDTO();
        ticketDTO.setType(SeatTypeEnum.TZ.code);
        ticketDTO.setNumber(args[25]);
        ticketDTOS.add(ticketDTO);
        ticketDTO = new TicketDTO();
        ticketDTO.setType(SeatTypeEnum.WZ.code);
        ticketDTO.setNumber(args[26]);
        ticketDTOS.add(ticketDTO);
        ticketDTO = new TicketDTO();
        ticketDTO.setType(SeatTypeEnum.YB.code);
        ticketDTO.setNumber(args[27]);
        ticketDTOS.add(ticketDTO);
        ticketDTO = new TicketDTO();
        ticketDTO.setType(SeatTypeEnum.YW.code);
        ticketDTO.setNumber(args[28]);
        ticketDTOS.add(ticketDTO);
        ticketDTO = new TicketDTO();
        ticketDTO.setType(SeatTypeEnum.YZ.code);
        ticketDTO.setNumber(args[29]);
        ticketDTOS.add(ticketDTO);
        ticketDTO = new TicketDTO();
        ticketDTO.setType(SeatTypeEnum.ZE.code);
        ticketDTO.setNumber(args[30]);
        ticketDTOS.add(ticketDTO);
        ticketDTO = new TicketDTO();
        ticketDTO.setType(SeatTypeEnum.ZY.code);
        ticketDTO.setNumber(args[31]);
        ticketDTOS.add(ticketDTO);
        ticketDTO = new TicketDTO();
        ticketDTO.setType(SeatTypeEnum.SWZ.code);
        ticketDTO.setNumber(args[32]);
        ticketDTOS.add(ticketDTO);
        ticketDTO = new TicketDTO();
        ticketDTO.setType(SeatTypeEnum.SRRB.code);
        ticketDTO.setNumber(args[33]);
        ticketDTOS.add(ticketDTO);
        return ticketDTOS;
    }
}
